﻿namespace TomatoBreak.Web
{
    using System;
    using System.Web.Mvc;

    using DataAccess;
    using DomainObjects;
    using Infrastructure;

    public class UserController : ApplicationController
    {
        private readonly IRepository<User> repository;
        private readonly IFormsAuthentication formsAuthentication;

        public UserController(IRepository<User> repository, IFormsAuthentication formsAuthentication)
        {
            if (repository == null)
            {
                throw new ArgumentNullException("repository");
            }

            if (formsAuthentication == null)
            {
                throw new ArgumentNullException("formsAuthentication");
            }

            this.repository = repository;
            this.formsAuthentication = formsAuthentication;
        }

        public ActionResult Create(CreateUserModel createModel)
        {
            if (createModel == null)
            {
                throw new ArgumentNullException("createModel");
            }

            EnsureUnique(createModel);

            if (!ModelState.IsValid)
            {
                return JsonModelStateErrors();
            }

            var user = new User(createModel.UserName, createModel.Password, createModel.Email);

            repository.Add(user);

            formsAuthentication.SignIn(createModel.UserName, false);

            return HttpCreated();
        }

        private void EnsureUnique(CreateUserModel createModel)
        {
            if (repository.Exists(u => u.UserName == createModel.UserName))
            {
                ModelState.AddModelError("userName", ErrorMessages.UsersController_DuplicateUserName);
            }
            else if (repository.Exists(u => u.Email == createModel.Email))
            {
                ModelState.AddModelError("email", ErrorMessages.UsersController_DuplicateEmail);
            }
        }
    }
}